package com.zz.push.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class PushClient {

    public static final String HOST = "localhost";
    private static final int PORT = 9527;
    private static Logger logger = LoggerFactory.getLogger(PushClient.class);

    public static void main(String[] args) throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();

        PushClient.connect(b, workerGroup);
    }

    static void connect(Bootstrap b, EventLoopGroup workerGroup) {
        logger.info("connect...");
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new PushClientChannelInitializer());

        b.remoteAddress(HOST, PORT);
        b.connect().addListener((ChannelFuture channelFuture) -> {
            if (channelFuture.cause() != null) {
                logger.info("Failed to connect: " + channelFuture.cause());
            }

            if (!channelFuture.isSuccess()) {
                logger.info("listener:Reconnect");
                workerGroup.schedule(() -> connect(b, workerGroup), 10L, TimeUnit.SECONDS);
            }
        });
    }

}
